var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var topictitle ="";
var topicid = "";
var app = getApp();
var uid = 0;
var uname = '';  //作者用户名
var wxFailAuth = true;
Page({
  data: {
      data:{},
      dslist:[], //打赏列表
      imgDomain: app.globalData.imgDomain,
      isFollow: false, //是否已关注
      isLiked: false, //是否已赞
      uid:0,  //当前登录用户Id
      token:'', //post请求时，当前登录用户token
      loginUname:'', //当前登录用户名
      commentMsg : '',
      replyid:0, //当前被回复的评论id
      openid:'',
      topicid:0,
      startTime: 0,
      hasShare: false,
      isShow: false,
      modalHidden: true
  },
  onReady: function(){
  },
  onLoad: function(data){
    topicid = data.topicid || "";
    this.setData({
        topicid: topicid
    })
    
    this.load(data);
  },
  load:function(options){
    var that = this;
    var inviteuid = options.inviteuid;
    //调用应用实例的方法获取全局数据
    app.LoginUserInfo(function(res){
      console.log("detail loginUserInfo:", res);
      wxFailAuth = res == -1;
      var share = options.inviteuid ? true : false;
      if(!wxFailAuth){
        var cata = (parseInt(res.usercata) > 0) ? true : false;
        //更新数据
        share = (share && cata) ? true : false;
        that.setData({
          uid:res.uid,
          token: res.token,
          loginUname:res.uname,
          openid:res.wxsmall_openid,
          hasShare: share
        })
        uid = res.uid;
      } else {
        that.setData({
          hasShare: share
        })
      }
    }, inviteuid);

    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "wxcheck"
      },
      success: function (responseData) {
        console.log("wxcheck :", responseData);
        that.setData({
          isShow: responseData.data.isShow
        });
      }
    });

    //动态详情
    util.api({
        data:{
            publickey:util.publiccode,
            ac:"topicdetail",
            topicid:topicid
        },
        success:function(responseData){                 
            var data = responseData.data;
            //处理时间
            var date = new Date(data.dateline*1000);
            data.formatDate = date.getFullYear()+"-"+(Number(date.getMonth())+1)+"-"+date.getDate();
            //处理语音
            if(data.audio) {                
                data.formatAudio = JSON.parse(data.audio);
            }
            //处理视频
            if(data.video) {
                data.formatVideo = data.video.split(",");
            }
            //处理message
            // data.message = data.message.replace(/\n/g, '\n\n');
            data.message = data.message.replace(/&nbsp;/g, '');
            //处理鉴定状态
            if(data.topictype == 1) {
                switch(data.status) {
                    case 1:
                        data.statusName = '真';
                        break;
                    case 2:
                        data.statusName = '假';
                        break;
                    case 3:
                        data.statusName = '无法鉴定';
                        break;
                    default:
                        data.statusName = '未鉴定';
                        break;
                }
            } else {                
                data.statusName = '';
            }
            //处理类型名称
            switch(data.topictype) {
                case 1:
                    data.topictypeName = '在线鉴定';
                    break;
                case 2:
                    data.topictypeName = '动态';
                    break;
                case 3:
                    data.topictypeName = '在线讲堂';
                    break;
                case 4:
                    data.topictypeName = '商品';
                    break;
                case 5:
                    data.topictypeName = '拍卖';
                    break;
                case 6:
                    data.topictypeName = '作品';
                    break;
                case 7:
                    data.topictypeName = '相册';
                    break;
                case 8:
                    data.topictypeName = '展览';
                    break;
                case 9:
                    data.topictypeName = '文字';
                    break;
                case 13:
                    data.topictypeName = '艺术年表';
                    break;
                case 14:
                    data.topictypeName = '荣誉奖项';
                    break;
                case 15:
                    data.topictypeName = '收藏拍卖';
                    break;
                case 16:
                    data.topictypeName = '公益捐献';
                    break;
                case 17:
                    data.topictypeName = '媒体报道';
                    break;
                case 18:
                    data.topictypeName = '出版刊登';
                    break;
            }
            topictitle = data.topictitle;
            uname = data.user.username;
            console.log(data);
            that.setData({
                data:data,
                isLiked:data.isLiked
            });            
            //当前用户是否已关注作者
            that.isFollow(uid, data.postuid);
            //当前用户是否已赞该动态
            that.isLike(uid);
        }
    });
    //打赏列表
    util.api({
        data:{
            publickey:util.publiccode,
            ac:"zslist",
            topicid:topicid,
            from:'smallwechat'
        },
        success:function(responseData){                 
            var data = responseData.data;
            if(data && data.length > 0) {
                that.setData({
                    dslist:data
                });
            }            
        }
    });
  },

  //重新读取登录用户数据
  reGetUserInfo: function (e) {
    var that = this;
    console.log("reGetUserInfo: ", e);
    if (e == 1) {
      // wx.reLaunch({ //用这个会报错fail can not invoke relaunch in background
      wx.redirectTo({
        url: '/pages/detail/detail?topicid=' + topicid
      })
    }
  },

  //是否已关注
  //uid是关注者  fid是被关注者
  isFollow: function(uid, fid) {
      var that = this;
    util.api({
        data:{
            publickey:util.publiccode,
            ac:"isaction",
            uid:uid,
            fid:fid
        },
        success:function(responseData){
            var data = responseData.data;
            if(data[0].rel == 2) {
                that.setData({
                    isFollow:true
                });
            }
        }
    });
  },
  //关注
  addFollow: function(e) {
    if (wxFailAuth) {
      app.reAuthorize(this.reGetUserInfo);
      return;
    }

      var that = this;
      var uid = e.currentTarget.dataset.uid;
      var fid = e.currentTarget.dataset.fid;
      var token = e.currentTarget.dataset.token;
      var privatekey = utilMd5.hexMD5(uid+'addaction'+token);
    util.api({
        data:{
            publickey:util.publiccode,
            ac:"addaction",
            uid:uid,
            tuid:fid,
            privatekey: privatekey
        },
        method:'POST',
        success:function(responseData){
            var data = responseData.data;
            if(data.res === true) {
                app.dialog('关注成功', 'success');
                that.setData({
                    isFollow: true
                });
            } else {
                app.dialog('关注失败', 'loading');
            }
        }
    });
  },
  //取消关注
  cancelFollow: function(e) {
      var that = this;
      var uid = e.currentTarget.dataset.uid;
      var fid = e.currentTarget.dataset.fid;
      var token = e.currentTarget.dataset.token;
      var privatekey = utilMd5.hexMD5(uid+'delaction'+token);
    util.api({
        data:{
            publickey:util.publiccode,
            ac:"delaction",
            uid:uid,
            tuid:fid,
            privatekey: privatekey
        },
        method:'POST',
        success:function(responseData){
            var data = responseData.data;
            if(data.res === true) {
                that.setData({
                    isFollow: false
                });
                app.dialog('取消关注成功', 'success');
            } else {
                app.dialog('取消关注失败', 'loading');
            }
        }
    });
  },
  //是否已赞
  isLike: function(uid) {
      var that = this;
    util.api({
        data:{
            publickey:util.publiccode,
            ac:"isliketopic",
            uid:uid,
            topicid:topicid
        },
        success:function(responseData){
            var data = responseData.data;
            if(data.res === true) {
                that.setData({
                    isLiked: true
                });
            }
        }
    });
  },
  //赞
  addLike: function(e) {
    if (wxFailAuth) {
      app.reAuthorize(this.reGetUserInfo);
      return;
    }
      var that = this;
      var uid = e.currentTarget.dataset.uid;
      var token = e.currentTarget.dataset.token;
      var privatekey = utilMd5.hexMD5(uid+'liketopic'+ token);
    util.api({
        data:{
            publickey:util.publiccode,
            ac:"liketopic",
            uid: that.data.uid,
            topicid:topicid,
            privatekey: privatekey
        },
        method:'POST',
        success:function(responseData){
            var data = responseData.data;
            if(data.res === true) {                
                that.setData({
                    isLiked: true
                });
                app.dialog('赞成功', 'success',that.refreshPage());
            } else {
                app.dialog('赞失败', 'loading');
            }
        }
    });
  },
  //取消赞
  cancelLike: function(e) {
      var that = this;
      var uid = e.currentTarget.dataset.uid;
      var token = e.currentTarget.dataset.token;
      var privatekey = utilMd5.hexMD5(uid+'delliketopic'+token);
    util.api({
        data:{
            publickey:util.publiccode,
            ac:"delliketopic",
            uid:uid,
            topicid:topicid,
            privatekey: privatekey
        },
        method:'POST',
        success:function(responseData){
            var data = responseData.data;
            if(data.res === true) {
                that.setData({
                    isLiked: false
                });
                app.dialog('取消赞成功', 'success',that.refreshPage());                
            } else {
                app.dialog('取消赞失败', 'loading');
            }
        }
    });
  },
  //评论
  inputMessage: function(e) {
    //把评论内容绑定到提交按钮上
    var val = e.detail.value;
    this.setData({
        commentMsg: val
    })
  },
  changeReplyid: function(e) {
    var val = e.currentTarget.dataset.id;
    var replyusername = e.currentTarget.dataset.uname;
    this.setData({
        replyid: val,
        commentMsg:  '@回复'+replyusername +':'    
    })  
  },
  addComment: function(e) {
    if (wxFailAuth) {
      app.reAuthorize(this.reGetUserInfo);
      return;
    }
        var that = this;
      var uid = e.currentTarget.dataset.uid;
      var token = e.currentTarget.dataset.token;
      var catatype = e.currentTarget.dataset.catatype;
      var replyid = e.currentTarget.dataset.replyid;      
      var message = e.currentTarget.dataset.message;
      if(!message) {
          app.dialog('请输入内容', 'loading');
          return;
      }
      var privatekey = utilMd5.hexMD5(uid+'topiccomment'+token);
    util.api({
        data:{
            publickey:util.publiccode,
            ac:"topiccomment",
            uid:uid,
            id:topicid,
            type:catatype,
            replyid:replyid,
            message:message,
            privatekey: privatekey
        },
        method:'POST',
        success:function(responseData){
            var data = responseData.data;
            console.log("评论 ：", data);
            var txt = replyid > 0 ? '回复':'评论';
            if(data.msg == 'true') {                
                that.setData({
                    isLiked: true
                });
                that.setData({
                    commentMsg: ''
                })

                app.dialog(txt+'成功', 'success',that.refreshPage());
            } else {
                app.dialog(txt+'失败', 'loading');
            }
        }
    });
  },
  //投诉
  complain: function(e) {
      app.dialog('投诉成功', 'success');
  },
  //页面分享
  onShareAppMessage: function () {
    return app.sharePage({
        title: topictitle?topictitle:uname,
        path: '/pages/detail/detail?topicid='+topicid+'&inviteuid='+uid
    });
  },
  //刷新当前页
  refreshPage: function() {
      wx.redirectTo({
          url:'/pages/detail/detail?topicid='+topicid
      })
  },
  //去赞赏页
  goRewardPage:function(e) {
    if (wxFailAuth) {
      app.reAuthorize(this.reGetUserInfo);
    } else {
      this.goAtherPage(e);
    }
  },

  //跳转
  goAtherPage: function(e){
      var url = e.currentTarget.dataset.link;
      wx.navigateTo({url: url,fail:function(e){console.log(e)}})
  },
  clickImg: function(e){
      this.setData({
          "stv.src":e.currentTarget.dataset.imgsrc,
          "stv.display":"true"
      });
  },
  goAtherPageRedirect: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.redirectTo({ url: url })
  },
  clickImg: function (e) {
    // this.setData({
    //     "stv.src":e.currentTarget.dataset.imgsrc,
    //     "stv.display":"true"
    // });
    var imgListType = e.currentTarget.dataset.imglist;
    var imgList = [];
    if (imgListType == "1"){
      var photo = this.data.data.photoscbk;
      for (var i = 0; i < photo.length ; i++){
        imgList = imgList.concat([photo[i].photo]);
      }
    } else if (imgListType == "2") {
      var photo = this.data.data.link_works;
      for (var i = 0; i < photo.length; i++) {
        imgList = imgList.concat(photo[i].photosData);
      }
    } else if (imgListType == "3") {
      var photo = this.data.data.link_relations;
      for (var i = 0; i < photo.length; i++) {
        imgList = imgList.concat(photo[i].photosData);
      }
    }
    console.log(imgList);
    wx.previewImage({
      current: e.currentTarget.dataset.imgsrc,
      urls: imgList
    })
  },

  //删除数据
  delDataAction:function(){
    this.setData({
      modalHidden: false,
    })
  },

  modalBindaconfirm: function () {
    this.deleteData();
    this.setData({
      modalHidden: true,
    })
  },
  modalBindcancel: function () {
    this.setData({
      modalHidden: true
    })
  },

  deleteData: function () {
    
    var that = this;

    var uid = this.data.uid;//用户id
    var token = this.data.token;//用户token
    var privatekey = utilMd5.hexMD5(uid + 'deltopic' + token);//私钥

    var params = {
      ac: "deltopic",
      privatekey: privatekey,
      uid: uid,
      topicid: that.data.data.id
    }
    console.log("deltopic params: ", params);
    util.api({
      method: "POST",
      data: params,
      success: function (responseData) {

        var result = responseData.data;
        console.log("del作品类别：", result);
        if (result.res) {
          app.dialog("删除成功", 'success', function(){
            wx.reLaunch({
              url: '/pages/index/index',
            })
          });
        }
      }
    });
  },

  editDataAction: function(){
    var that = this;
    var topicType = that.data.data.topictype;
    var pageUrl = '';
    var topicData = JSON.stringify(that.data.data);
    if(topicType == 6){//作品
      pageUrl = "/pages/release-zp/release-zp?data=" + topicData;
    } else if (topicType == 7 || topicType == 2){//相册／动态
      pageUrl = "/pages/release-jk/release-jk?data=" + topicData;
    } else if (topicType == 8 ) {//展览
      pageUrl = "/pages/release-jj/release-jj?data=" + topicData;
    } else if (topicType == 9) {//文字
      pageUrl = "/pages/release-wz/release-wz?data=" + topicData;
    } else if (topicType == 13) {//艺术年表
      pageUrl = "/pages/release-jj/release-jj?data=" + topicData;
    } else if (topicType == 14) {//荣誉奖项
      pageUrl = "/pages/release-jj/release-jj?data=" + topicData;
    } else if (topicType == 15) {//收藏拍卖
      pageUrl = "/pages/release-jj/release-jj?data=" + topicData;
    } else if (topicType == 16) {//公益捐赠
      pageUrl = "/pages/release-jj/release-jj?data=" + topicData;
    } else if (topicType == 17) {//媒体
      pageUrl = "/pages/release-mt/release-mt?data=" + topicData;
    } else if (topicType == 18) {//出版刊登
      pageUrl = "/pages/release-jj/release-jj?data=" + topicData;
    } else if (topicType == 19) {//工作经历
      pageUrl = "/pages/create/create?status=gzjl&data=" + topicData;
    } else if (topicType == 20) {//教育经历
      pageUrl = "/pages/create/create?status=jyjl&data=" + topicData;
    } 

    if(pageUrl){
      wx.navigateTo({
        url: pageUrl,
      })
    }
  }
})